require "skynet.manager"

local skynet = require "skynet"
local queue = require "skynet.queue"

local CMD = {}
local log_list = {}
local fp_list = {} --文件句柄
local cs = queue()
local open_file = open_file
local maxsize = 10 *1024*1024 --文件最大M
local fileId = 1
--保存到文件
local function save(data)
	local file = data[1]
	local msg = data[2]
    if file and msg then
        local fp = fp_list[file] 
        if not fp then   
        	fp = open_file(file, "a")
        	fp_list[file] = fp            
        end
        if fp then
			fp:write(msg)
			fp:flush()
			local fileSize = fp:seek("end")
			if fileSize >= maxsize then
				--分割文件				
				local rename = tostring(os.date("%Y%m%d_%H%M")) .. "_"..fileId
				fileId = fileId + 1				
				fp:close()
				fp_list[file] = nil
				local path = get_file_paht(file)
				path = path..get_file_cname(file) .. "_" .. rename .. get_file_ext(file)
				os.rename(file, path)
			end			
			
		end      	
    end
end

---------------------------------------------------------
-- LUA Command
---------------------------------------------------------

function CMD.start(conf)
end

function CMD.stop( )
	--logger.exit()
	for k,v in pairs(fp_list) do 
		if v then 
			v:close()
			fp_list[k] = nil
		end
	end
end

function CMD.debug(name, msg)
	table.insert(log_list,{name,msg})
end

function CMD.info(name, msg)
	
end

function CMD.warning(name, msg)
	
end

function CMD.error(name, msg)	
	table.insert(log_list,{name,msg})
end

function CMD.fatal(name, msg)
	
end

function CMD.tick()
	if log_list[1] then
		save(log_list[1])
		-- log_list[1] = nil
		table.remove(log_list,1)
	end
end

---------------------------------------------------------
-- skynet
---------------------------------------------------------
local function loop()
	while true do		
		if log_list[1] then
			skynet.send(skynet.self(), 'lua', 'tick')
		end
		skynet.sleep(50)--
	end
end

skynet.start(function()
	skynet.fork(loop)	

	local f = dispatch_command(CMD)
	function _queue( session, source, cmd, ...)		
		local resut = cs(f,session, source, cmd, ...)
		return result
	end
	skynet.dispatch("lua", _queue)
	skynet.register "log_manager"
end)